package com.central.apps.handler.contract;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.central.app.common.cache.CfgRedisCache;
import com.central.app.entity.TBFile;
import com.central.app.model.BizApp;
import com.central.app.service.CheckConNodeService;
import com.central.app.service.FlowCommonService;
import com.central.app.service.HandlerService;
import com.central.apps.common.util.FileUtil;
import com.central.bizcommon.constant.MessageConstant;
import com.central.common.auth.details.LoginAppUser;
import com.central.common.exception.business.BusinessException;
import com.central.common.exception.service.ServiceException;
import com.central.common.util.SysUserUtil;
import com.central.common.util.ToolUtil;
import com.central.common.web.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.*;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Slf4j
@Component
public class ConUtil {
    @Autowired
    private HandlerService handlerService;
    @Autowired
    private CheckConNodeService checkConNodeService;
    @Autowired
    private CfgRedisCache cfgRedisCache;
    @Autowired
    private FlowCommonService commonService;
    //针对于合同签订使用
    public void moveFile(int conid, String appname, String app, long id, String conname) throws FileNotFoundException {
        LoginAppUser user = SysUserUtil.getLoginAppUser();
        //部门编码
        String deptcode = user.getDeptcode();
        String username = user.getUsername();
        String deptName = user.getDeptName();
        if (ToolUtil.isEmpty(deptName)) {
            List<Map<String, Object>> deptList = handlerService.findBySql("select fullname from sys_dept where code ='" + deptcode + "'");
            if (CollectionUtils.isNotEmpty(deptList)) {
                deptName = MapUtils.getString(deptList.get(0), "fullname");
            }
        }
        Long userid = user.getId();
        String sql = "select id from gq_conaccount where conid ='" + conid + "'";
        String like = "  and (filerealname like '%合同申请%'||filerealname like '%合同评审%'  )";
        List<Map<String, Object>> templateList = handlerService.findBySql(sql);
        String tmpId = MapUtil.getStr(templateList.get(0), "id");//合同申请或者合同台账主键id
        List<Map<String, Object>> fileList = handlerService.findBySql("select * from tb_file where isshow=1 and  appname = '" + appname + "' and recordid =" + tmpId + like + " order by statustime desc");

        //取第一个，最新的合同版本
        if (CollectionUtils.isNotEmpty(fileList)) {
            for (int i = 0; i < 1; i++) {
                Integer pathid = MapUtil.getInt(fileList.get(i), "pathid");
                String filesize = MapUtil.getStr(fileList.get(i), "filesize");
                String pathname = MapUtil.getStr(fileList.get(i), "filepath");
                String extensionname = MapUtil.getStr(fileList.get(i), "extensionname");//文件类型
                String filename = MapUtil.getStr(fileList.get(i), "filename");
                String filerealname = MapUtil.getStr(fileList.get(i), "filerealname");

                //合同文本变更只变更doc或者docx类型的文件
                if (!"docx".equals(extensionname) && !"doc".equals(extensionname)) {
                    continue;
                }
                List<Map<String, Object>> pathList = handlerService.findBySql("select * from tb_path where pathid =" + pathid + "");
                String filepath = MapUtil.getStr(pathList.get(0), "pathname");
                if (StringUtils.isNotBlank(pathname)) {
                    String[] split = pathname.split("/");
                    pathname = "/" + split[split.length - 1];
                }
                String pt = filepath + pathname;
                //
                InputStream is = new FileInputStream(pt);
                String uid = IdUtil.simpleUUID();
                SimpleDateFormat sdft = new SimpleDateFormat("yyyy-MM-dd");
                String formatNowDate = sdft.format(new Date());
                String fileName = formatNowDate + "_" + uid + "." + extensionname;
                String fileallpath = "/home/eam/doclinks/" + deptName + "/" + fileName;
                FileUtil.copy(pt, fileallpath);
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                // 插入DB
                TBFile tbFile = new TBFile();
                tbFile.setPathid(pathid);
                if (StringUtils.isNotBlank(deptcode)) {
                    tbFile.setDeptid(deptcode);
                }
                if (StringUtils.isNotBlank(deptName)) {
                    tbFile.setDeptfullname(deptName);
                } else {
                    tbFile.setDeptfullname("科技发展部");
                }
                if (userid != null) {
                    tbFile.setUserid(String.valueOf(userid));
                }
                if (StringUtils.isNotBlank(username)) {
                    tbFile.setUsername(username);
                }
                String fileMd5 = FileUtil.fileMD5(new File(fileallpath));
                tbFile.setUploadtime(new Date());
                tbFile.setFilesize(new BigDecimal(filesize));
                tbFile.setFilepath("/" + deptName + "/" + fileName);
                tbFile.setExtensionname(extensionname);
                BizApp appinfo = cfgRedisCache.getCacheApp(app);
                tbFile.setAppid(appinfo.getId().intValue());
                tbFile.setAppname(app);
                tbFile.setRecordid(id);
                tbFile.setFilestatus("已发布");
                tbFile.setStatustime(new Date());
                if (StringUtils.isNotBlank(conname)) {
                    tbFile.setFilename(conname);
                    tbFile.setFilerealname(conname + "." + extensionname);
                } else {
                    tbFile.setFilename(filename);
                    tbFile.setFilerealname(filerealname);
                }
                tbFile.setFileversion(1);
                tbFile.setMd5(fileMd5);
                tbFile.setSecretkey("");
                tbFile.setIsshow(1);
                checkConNodeService.insertConfiles(tbFile);
            }
        }
    }

    //通用的文件转移方法，
    public void moveFile(String fromapp, long fromid, String app, long id) throws FileNotFoundException {
        //先删除，在添加
        handlerService.updateBySql("update tb_file  set isshow =0 where recordid = "+id+" and appname ='"+app+"'");
        LoginAppUser user = SysUserUtil.getLoginAppUser();
        //部门编码
        String deptcode = user.getDeptcode();
        String username = user.getUsername();
        String deptName = user.getDeptName();
        if (ToolUtil.isEmpty(deptName)) {
            List<Map<String, Object>> deptList = handlerService.findBySql("select fullname from sys_dept where code ='" + deptcode + "'");
            if (CollectionUtils.isNotEmpty(deptList)) {
                deptName = MapUtils.getString(deptList.get(0), "fullname");
            }
        }
        Long userid = user.getId();
        List<Map<String, Object>> fileList = handlerService.findBySql("select * from tb_file where isshow=1 and  appname = '" + fromapp + "' and recordid =" + fromid + " order by statustime desc");

        //取第一个，最新的合同版本
        if (CollectionUtils.isNotEmpty(fileList)) {
            for (int i = 0; i < 1; i++) {
                Integer pathid = MapUtil.getInt(fileList.get(i), "pathid");
                String filesize = MapUtil.getStr(fileList.get(i), "filesize");
                String pathname = MapUtil.getStr(fileList.get(i), "filepath");
                String extensionname = MapUtil.getStr(fileList.get(i), "extensionname");//文件类型
                String filename = MapUtil.getStr(fileList.get(i), "filename");
                String filerealname = MapUtil.getStr(fileList.get(i), "filerealname");
                List<Map<String, Object>> pathList = handlerService.findBySql("select * from tb_path where pathid =" + pathid + "");
                String filepath = MapUtil.getStr(pathList.get(0), "pathname");
                if (StringUtils.isNotBlank(pathname)) {
                    String[] split = pathname.split("/");
                    pathname = "/" + split[split.length - 1];
                }
                String pt = filepath + pathname;
                //
                InputStream is = new FileInputStream(pt);
                String uid = IdUtil.simpleUUID();
                SimpleDateFormat sdft = new SimpleDateFormat("yyyy-MM-dd");
                String formatNowDate = sdft.format(new Date());
                String fileName = formatNowDate + "_" + uid + "." + extensionname;
                String fileallpath = "/home/eam/doclinks/" + deptName + "/" + fileName;
                FileUtil.copy(pt, fileallpath);
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                // 插入DB
                TBFile tbFile = new TBFile();
                tbFile.setPathid(pathid);
                if (StringUtils.isNotBlank(deptcode)) {
                    tbFile.setDeptid(deptcode);
                }
                if (StringUtils.isNotBlank(deptName)) {
                    tbFile.setDeptfullname(deptName);
                } else {
                    tbFile.setDeptfullname("科技发展部");
                }
                if (userid != null) {
                    tbFile.setUserid(String.valueOf(userid));
                }
                if (StringUtils.isNotBlank(username)) {
                    tbFile.setUsername(username);
                }
                String fileMd5 = FileUtil.fileMD5(new File(fileallpath));
                tbFile.setUploadtime(new Date());
                tbFile.setFilesize(new BigDecimal(filesize));
                tbFile.setFilepath("/" + deptName + "/" + fileName);
                tbFile.setExtensionname(extensionname);
                BizApp appinfo = cfgRedisCache.getCacheApp(app);
                tbFile.setAppid(appinfo.getId().intValue());
                tbFile.setAppname(app);
                tbFile.setRecordid(id);
                tbFile.setFilestatus("已发布");
                tbFile.setStatustime(new Date());
                tbFile.setFilename(filename);
                tbFile.setFilerealname(filerealname);
                tbFile.setFileversion(1);
                tbFile.setMd5(fileMd5);
                tbFile.setSecretkey("");
                tbFile.setIsshow(1);
                checkConNodeService.insertConfiles(tbFile);
            }
        }
    }

    //多对一 移动 通用的文件转移方法，
    public void moveFile(String fromapp, String fromids, String app, long id) throws FileNotFoundException {
        String[] fromid = fromids.split(",");
        for (String s : fromid) {
            moveFile(fromapp, Long.valueOf(s), app, id);
        }
    }
    //文件列表插入默认初始值
    public void setlistfile(int id,String appname,int conid) throws Exception {
        List<Map<String, Object>> list = handlerService.findBySql("select paramname from gq_pcline where paramcode ='"+appname+"'");
        if(CollectionUtils.isNotEmpty(list)){
            for (Map<String, Object> stringObjectMap : list) {
                Map<String,Object> map = new HashMap<>();
                map.put("pid",id);
                //map.put("conid",conid);//conid是 交付物使用字段，不可以给他赋值，要不然，交付物那边也会显示
                map.put("appname",appname);
                map.put("status","未上传");
                map.put("taskdelname",stringObjectMap.get("paramname"));
                handlerService.insert("gq_filelist",map);
            }

        }
    }
    //获取当前责任人
    public String getUsersInfo(String app,long id){
        StringBuffer executors = new StringBuffer();
        List<Map<String, Object>> users = null;
        try {
            users = commonService.findNowExecutors(app, id);
            if(CollectionUtils.isNotEmpty(users)){
                for (Map<String, Object> user : users) {
                   executors.append(user.get("id")).append(",");
                }
            }
        } catch (Exception e) {
            // TODO: handle exception
            log.error(e.getMessage(), e);

        }
        return executors.toString();
    }
    //
}

